package org.springframework.cloud.gateway;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Optional;
import java.util.function.Consumer;


/**
 * @author Spencer Gibb
 */
@Slf4j
@RestController
public class GatewayController {

/*
	private final WebClient webClient;
	private final DataBufferFactory bufferFactory;

	public GatewayController() {
		webClient = WebClient.builder().build();
		bufferFactory = new DefaultDataBufferFactory();
	}

	@GetMapping(path = "/")
	public Flux<HttpBin> home(ServerWebExchange exchange) {

		System.out.print("开始======");
//		return this.webClient.get().uri("http://httpbin.org/get").retrieve().bodyToFlux(HttpBin.class);


		return this.webClient.get().uri("http://httpbin.org/get") .accept(MediaType.APPLICATION_STREAM_JSON) // 2
				.exchange() // 3
				.flatMapMany(response -> response.bodyToFlux(HttpBin.class))   // 4
				.doOnNext(System.out::println)  // 5
				;   //

	}
*/

	private final WebClient webClient;

	public GatewayController(WebClient webClient) {
		this.webClient = webClient;
	}

	//TODO: plugin to request mappings
	@GetMapping(path = "/")
	public Flux<HttpBin> home(ServerWebExchange exchange) {
		String requestUrl= exchange.getAttribute("requestUrl");
//		ServerHttpRequest request = exchange.getRequest();
	  HttpHeaders httpHeaders= exchange.getRequest().getHeaders();

//		Consumer<HttpHeaders> consumer= p ->p.addAll(httpHeaders);
//		httpHeaders.forEach((name, values) -> values.forEach(value -> log.info("{}={}", name, value)));
//		Consumer
		return this.webClient.get().uri(requestUrl).headers(httpHeaders1 -> {}).accept(MediaType.APPLICATION_STREAM_JSON) // 2
				.exchange() // 3
				.flatMapMany(response -> response.bodyToFlux(HttpBin.class))   // 4
				.doOnNext(System.out::println)  // 5
				;   //
	}

}
